package com.ocm.tourism.core.dao.jpa;


import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.ocm.tourism.core.dao.AuditInfoDao;
import com.ocm.tourism.core.domain.AuditBusinessAdvs;
import com.ocm.tourism.core.domain.AuditInfo;
import com.ocm.tourism.core.domain.TransalationType;


@Repository("auditDao")
public class JpaAuditInfoDao extends JpaGenericDao<AuditInfo> implements AuditInfoDao {

   public JpaAuditInfoDao() {
      this.setClazz(AuditInfo.class);
   }

   @Override
   public boolean hasExistedAudit(String auditKey) {
      Query query = this.entityManager().createQuery("SELECT COUNT(a) FROM AuditInfo a WHERE a.auditKey =:auditKey", Long.class);
      query.setParameter("auditKey", auditKey);
      long count = (Long) query.getSingleResult();
      if (count > 0)
         return true;
      return false;
   }

   @Override
   public long getNextIndex(TransalationType transalationType) {
      Query query = this.entityManager().createQuery("SELECT (max(a.lastIndex) + 1) FROM AuditBusinessAdvs a WHERE a.transalationType =:transalationType", Long.class);
      query.setParameter("transalationType", transalationType);
      long nextIndex = (Long) query.getSingleResult();
      return nextIndex;
   }

   @SuppressWarnings("unchecked")
   @Override
   public AuditBusinessAdvs find(long businessId, TransalationType transalationType) {
      Query query = this.entityManager().createQuery("SELECT a FROM AuditBusinessAdvs a WHERE a.transalationType =:transalationType and a.foreignKey =:foreignKey", AuditBusinessAdvs.class);
      query.setParameter("transalationType", transalationType);
      query.setParameter("foreignKey", businessId);
      List<AuditBusinessAdvs> auditBusinessAdvs = query.getResultList();
      if (auditBusinessAdvs.size() > 0){
         return auditBusinessAdvs.get(0);
      }
      return null;
   }

   @Override
   public void saveAuditBusinessAdvs(AuditBusinessAdvs auditBusinessAdvs) {
      if (auditBusinessAdvs.getId() != null && auditBusinessAdvs.getId() > 0)
         this.entityManager().merge(auditBusinessAdvs);
      else
         this.entityManager().persist(auditBusinessAdvs);
   }
}
